import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useAppStore } from '@/stores/app'

NProgress.configure({ showSpinner: false }) // 进度条

// 白名单路由
const whiteList = ['/login']
//
const loadComponent = import.meta.glob('./views/**/**.vue')

type routeType = {
  url: string
  name: string
  path: string
  type: number
  status: number
  title: string
  icon: string
  children: routeType[]
}
const addRoute = (routes: routeType[]) => {
  if (routes.length > 0) {
    routes.forEach((route) => {
      if (route.type != 1 && route.status == 1) {
        const nav = {
          path: route.url,
          name: route.name,
          meta: { name: route.name, title: route.title, icon: route.icon },
          component: loadComponent[`./views${route.path}.vue`]
        }
        router.addRoute('layout', nav)
      }
      if (route.children.length > 0) {
        addRoute(route.children)
      }
    })
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const appStore = useAppStore()
  if (appStore.token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasMenus = appStore.menus && appStore.menus.length > 0
      if (hasMenus) {
        // 未匹配到任何路由，跳转404
        if (to.matched.length === 0) {
          from.name ? next({ name: from.name }) : next('/404')
        } else {
          next()
        }
      } else {
        try {
          const result: any = await appStore.getMenus()
          addRoute(result.data)
          next({ ...to, replace: true })
        } catch (error) {
          // 移除 token 并跳转登录页
          appStore.logout()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
